package com.zhouyu.protocol;

import com.zhouyu.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {

    // 发送请求
    public String send(String hostname, Integer port, Invocation invocation) throws IOException {
        // 用户的配置

        try {

            // 创建URL对象
            URL url = new URL("http", hostname, port, "/");
            // 打开连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            httpURLConnection.setRequestMethod("POST");
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true
            httpURLConnection.setDoOutput(true);

            // 配置
            // 获取输出流
            OutputStream outputStream = httpURLConnection.getOutputStream();
            // 创建对象输出流
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            // 将invocation对象写入输出流
            oos.writeObject(invocation);
            // 刷新输出流
            oos.flush();
            // 关闭输出流
            oos.close();

            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            // 将输入流转换为字符串
            String result = IOUtils.toString(inputStream);
            // 返回结果
            return result;
        } catch (MalformedURLException e) {

        } catch (IOException e) {
            // 抛出异常
            throw e;

        }

        // 返回null
        return null;
    }
}
